package dpss.server.udp;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.Serializable;

/**
 * The server to server UDP communication message
 * 
 * @author musab.mirza
 *
 */
public class UDPMessage implements Serializable {
	
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private String message;
	private Object data;
	private boolean success;
	private String errorMessage;
	
	// The byte size defined for this type
	public static final Integer BYTE_SIZE = 1024; 
	
	
	
	/**
	 * Init with data and details
	 * 
	 * @param message
	 * @param data
	 * @param success
	 * @param errorMessage
	 */
	public UDPMessage(String message, Object data, boolean success, String errorMessage){
		this.message = message;
		this.data  = data;
		this.success = success;
		this.errorMessage = errorMessage;
	}


	/**
	 * @return the message
	 */
	public String getMessage() {
		return message;
	}


	/**
	 * @param message the message to set
	 */
	public void setMessage(String message) {
		this.message = message;
	}


	/**
	 * @return the data
	 */
	public Object getData() {
		return data;
	}


	/**
	 * @param data the data to set
	 */
	public void setData(Object data) {
		this.data = data;
	}


	/**
	 * Convert this object to bytes for transfer
	 * @return
	 */
	public byte[] getBytes() {
		ByteArrayOutputStream bStream = new ByteArrayOutputStream();
		ObjectOutput oo = null;
		try {
			oo = new ObjectOutputStream(bStream);
			oo.writeObject(this);
		} catch (IOException e) {
			e.printStackTrace();
		}
		return bStream.toByteArray();
	}



	/**
	 * Convert from bytes to a UDP message
	 * @param bytes
	 * @return
	 */
	public static UDPMessage getFromBytes(byte[] bytes) {
		UDPMessage message = null;
		ObjectInputStream iStream;
		try {
			iStream = new ObjectInputStream(new ByteArrayInputStream(bytes));
			message = (UDPMessage) iStream.readObject();
			iStream.close();
		} catch (IOException | ClassNotFoundException e1) {
			e1.printStackTrace();
		}
		return message;
	}




	/**
	 * @return the errorMessage
	 */
	public String getErrorMessage() {
		return errorMessage;
	}




	/**
	 * @param errorMessage the errorMessage to set
	 */
	public void setErrorMessage(String errorMessage) {
		this.errorMessage = errorMessage;
	}




	/**
	 * @return the success
	 */
	public boolean isSuccess() {
		return success;
	}




	/**
	 * @param success the success to set
	 */
	public void setSuccess(boolean success) {
		this.success = success;
	}

}
